﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PhotoGalleryEnteties;
using PhotogalleryModel;
using photogalleryMVC.Controllers;

namespace photogalleryMVC.Filters
{
    public class UpdateSubscribeAttribute:ActionFilterAttribute
    {
        private string _idFieldName;

        public UpdateSubscribeAttribute (string idFieldName)
        {
            _idFieldName = idFieldName;
        }
        
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            PhotoGalleryController  controller = (PhotoGalleryController) filterContext.Controller;
            if (controller.User.Identity.IsAuthenticated)
            {
                GalleryUser user = controller.UserRepository.GetUserByName(controller.User.Identity.Name);
                if (!filterContext.ActionParameters.ContainsKey(_idFieldName))
                    throw new ArgumentException(string.Format("parameter with id{0} does not exist", _idFieldName));
                int id = (int) filterContext.ActionParameters[_idFieldName];
                controller.SubscribeRepository.UpdateSubscribe(user.UserId, id, DateTime.Now);
            }

        } 
    }

    
}